import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Button, Skeleton, Image, message, Upload, Row, Col, Form, Select } from 'antd'
import { UploadOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ProFormText,
  ProForm,
  ProFormDatePicker,
  ProFormDateTimePicker,
  ProFormSelect,
  ProFormTextArea,
  ProFormRadio,
  ProFormDependency
} from '@ant-design/pro-components';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { information } from '@/utils/rules';
import Utils from 'fr-util/utils';
import CheckListButton from '@/components/CheckListButton'

import {
  reqPulseCalibrationList,
  reqTongueCalibrationList,
  reqDiagnosisTermList,
  reqDiagnosisTermListByGrade,
  reqSeniorInquiryList,
  reqSeniorInquiryUpdate,
  reqSymptomList,
  reqSymptomListByGrade
} from '@/services/firstConsultation';

import {
  reqPatientList,
  reqDetal,
  reqUpdate,
  reqPulseUpdate,
  reqPulseDetail,
  reqPulseList,
  reqQuestionTermList,
  reqIllnessList
} from '@/services/basicConsultation';


const EditModal: React.FC = ({ row, isOpen, handleModal }) => {
  const title = '追加问题'
  const [data, setData] = useState([])
  const [formObj] = ProForm.useForm()
  // const handleAdd = async (params: any) => {
  //   const res = await reqAddActPrize({ ...params })
  //   if (res.code == 200) {
  //     message.success(res?.message)
  //     actionRef?.current.reload()
  //     handleModal(false)
  //   } else {
  //     message.error(res?.message)
  //   }
  // }

  const handleEditor = async (params: any) => {
    console.log('handleEditor :>> ', params);

    const initArr = row?.basicInquiryJson || [];
    initArr.push({
      question: params?.question,
      value: params?.value[0],
    })

    handleModal(initArr)
  }


  // async function init(query: { tyPatientId: string, tyMedicalCaseId?: string }) {
  //   try {
  //     const res = await reqPulseCalibrationList({
  //       pageNum: 1,
  //       pageSize: 10,
  //       ...query
  //     })

  //     if (res?.resultCode == '00000000') {
  //       let lOptions = [];
  //       let rOptions = [];
  //       res?.data?.result?.map((item) => {
  //         if (item.type == '1') {
  //           lOptions.push({
  //             label: item?.name,
  //             value: item?.name
  //           })
  //         } else {
  //           rOptions.push({
  //             label: item?.name,
  //             value: item?.name
  //           })
  //         }
  //       })

  //       seLeftOptions(lOptions);
  //       setRightOptions(rOptions);
  //       if (row?.seniorInquiry?.tyPulseCalibrationName) {
  //         setinitialValues(row?.seniorInquiry?.tyPulseCalibrationName)
  //       }
  //     } else {
  //       message.error(`获取脉诊标定列表信息出错！${res?.message}`)
  //     }
  //   } catch (error: any) {
  //     message.error('获取脉诊标定列表信息出错！', error)
  //     console.log('获取脉诊标定列表信息出错！ :>> ', error);
  //   }
  // }

  // useEffect(() => {
  //   init()
  // }, [])

  async function init() {
    try {
      const res = await reqQuestionTermList({
        pageNum: 1,
        pageSize: 10,
        // dept: "内科",
        // type: 1
      })

      console.log('病种病名列表信息 :>> ', res?.data);
      if (res?.resultCode == '00000000') {
        setData(res?.data?.result)
      } else {
        message.error(`病种病名列表信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('病种病名列表信息出错！', error)
      console.log('病种病名列表信息出错！ :>> ', error);
    }
  }


  useEffect(() => {
    if (row?.id) {
      console.log('user ==========:>> ', row);
      init()
    }
  }, [row])

  function jsonToarray(jsonArr: string) {
    const arr = JSON.parse(jsonArr);
    return arr.map((item: string) => ({
      label: item,
      value: item
    }))
  }



  const valueChanage = (value: any) => {
    console.log('valueChanage :>> ', value);
  }

  console.log('row :>> ', row);


  const prenterList = data.map((item, index) => {
    return ({
      label: item?.question,
      value: item?.question
    })
  })

  async function getList1(query = {}) {
    const res = await reqQuestionTermList({
      ...query,
      pageNum: 1,
      pageSize: 10
    });
    const mapArr = res?.data?.result?.map((item: any) => ({
      label: item?.question,
      value: item?.question
    }))
    return mapArr;
  }

  const optionsMap = useMemo(() => {
    let obj = {};
    data.map((item) => {
      obj[item?.question] = item
    })
    return obj;
  }, [data])


  return (
    <Modal
      width={680}
      title={title}
      open={isOpen}
      onCancel={() => handleModal()}
      footer={null}
      destroyOnClose={true}
    >
      <ProForm
        form={formObj}
        onFinish={(values): Promise<any> => handleEditor(values)}
      >

        {/* <ProForm.Item
          label="问题类型"
          name="type"
        >
          <CheckListButton
            options={[
              {
                label: '症状',
                value: '1',
              },
              {
                label: '自拟定',
                value: '2',
              },
              {
                label: '国际问题',
                value: '3',
              },
            ]}
            isRadio
          />
        </ProForm.Item> */}

        <ProFormSelect
          label="问题类型"
          name="type"
          options={[
            {
              label: '症状',
              value: '1',
            },
            {
              label: '自拟定',
              value: '2',
            },
            {
              label: '国际问题',
              value: '3',
            },
          ]}
        />
        <ProFormDependency
          name={['type']}
          shouldUpdate={(prevValues, curValues) => {
            if (prevValues.type !== curValues.type) {
              formObj.setFieldValue('question', undefined)
              return true
            } else {
              return false
            }
          }}
        >
          {({ type }) => {
            return (
              /* type && */ <ProFormSelect
                label="选择问题"
                params={{ type/* : type && type[0] && type[0] */ }}
                name="question"
                request={getList1}
              />
            );
          }}
        </ProFormDependency>


        {/* <Form.Item
          shouldUpdate={(prevValues, curValues) => prevValues.question !== curValues.question}
        >
          {(arg) => {
            if (!arg.getFieldValue('question')) return null;
            const jsonArr = optionsMap[arg.getFieldValue('question')]?.optionAnswer;
            console.log('optionsMap :>> ', optionsMap, arg.getFieldValue('question'));
            const op = jsonToarray(jsonArr);
            return (
              <>
                <Form.Item
                  label="选择答案"
                  name="value"
                  rules={[{
                    required: true
                  }]}
                >
                  <CheckListButton
                    options={op}
                    isRadio
                  />
                </Form.Item>
                <Button type="primary" htmlType="submit">确定</Button>
              </>
            );
          }}
        </Form.Item> */}
        <ProFormDependency

          name={['question']}
        >
          {({ question }) => {
            if (!question) return null;
            const jsonArr = optionsMap[question]?.optionAnswer;
            console.log('optionsMap :>> ', optionsMap, question);
            const op = jsonToarray(jsonArr);
            return (
              <ProForm.Item
                label="选择答案"
                name="value"
              >
                <CheckListButton
                  options={op}
                  isRadio
                />
              </ProForm.Item>
            );
          }}
        </ProFormDependency>
      </ProForm>
    </Modal>

  );
};
export { EditModal }

